package com.web;


import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.service.FileService;

public class DownLoad extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String id=request.getParameter("id");
		
		FileService fileService=new FileService();
		com.entity.File f=fileService.getById(id);
		
		File file=new File("c:/file/"+f.getFilename());
		BufferedInputStream inputStream=new BufferedInputStream(new FileInputStream(file));
		byte[] buffer=new byte[1024];
		
		OutputStream outputStream=response.getOutputStream();
		
		response.setContentType("application/octet-stream");
		response.setHeader("Content-Length", file.length()+"");
		
		String fileName = f.getName();
		String encodedfileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
		response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedfileName + "\"");
		
		
		int len=-1;
		while((len=inputStream.read(buffer))!=-1){
			outputStream.write(buffer,0,len);
		}
		
		outputStream.flush();
		outputStream.close();
		inputStream.close();
		
	}

}
